package com.mgface.zookeeper.premitive;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class 任务热备份 {
	private static Logger log = Logger.getLogger(任务热备份.class);
	private static ZooKeeper client;
	private static String path = "/zk";
	private static String newpath;

	public static void main(String[] args) throws Exception {
		CountDownLatch on = new CountDownLatch(1);
		client = new ZooKeeper("localhost:2181,localhost:2182,localhost:2183", 10_000, e -> {
			try {
				if (e.getState() == KeeperState.SyncConnected) {
					switch (e.getType()) {
					case None:
						if (e.getPath() == null) {
							on.countDown();
						}
						break;
					case NodeChildrenChanged:
						List<String> list = client.getChildren(path, true);// 获取子节点的相对路径，并且监听子节点的列表变化
						Collections.sort(list);
						log.info("当前节点集合:" + list);
						String root = e.getPath();
						String firstnode = root + "/" + list.get(0);//小序号优先
						if (firstnode.equals(newpath)) {
							String status = new String(client.getData(firstnode, false, null));
							if (!"running".equals(status)) {
								client.setData(firstnode, "running".getBytes(), -1);
							}
						}
						log.info("running状态节点,k:v" + firstnode + "/"+ new String(client.getData(firstnode, false, null)) 
								+ "|当前节点状态:k:v" + newpath + "/"+ new String(client.getData(newpath, false, null)));
						break;
					default:
						break;
					}
				}
			} catch (Exception error) {
				error.getMessage();
			}

		});
		log.info("ZK状态:" + client.getState().toString());
		on.await();
		log.info("zookeeper session 建立完成");
		Stat stat = client.exists(path, false);
		if (stat == null) {
			client.create(path, "root".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		}
		client.getChildren(path, true);
		newpath = client.create(path + "/z2", "standby".getBytes(), Ids.OPEN_ACL_UNSAFE,
				CreateMode.EPHEMERAL_SEQUENTIAL);
		log.info(newpath);
		TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
	}
}
